package com.test.mess;

import lombok.extern.slf4j.Slf4j;

import java.io.*;
import java.util.Arrays;

@Slf4j
public class ReadLog {

    public static void main(String[] args) throws Throwable {
        String key = "error";
/*
        // 从指定文件里获取关键字
        List<String> files = Lists.newArrayList();
        files.add("C:\\Users\\zhangdan\\Desktop\\customer-public-dubbo-2019-11-26-0.log");
        files.add("C:\\Users\\zhangdan\\Desktop\\customer-public-dubbo-2019-11-26-0_1.log");
        // Arrays.stream(args)
        files.forEach(f -> getLog(f, key));*/

        // 从文件夹里搜索关键字
        //  D:\log\ C:\Users\zhangdan\Downloads\
        Arrays.stream(new File("D:\\logs\\20191209")
                .listFiles(f -> f.getName().contains(".log"))).forEach(f -> getLog(f, key));
//        Arrays.stream(new File("D:\\logs\\20191209").listFiles())
//                .forEach(o -> Arrays.stream(o.listFiles(f -> f.getName().contains(".log"))).forEach(f -> getLog(f, key)));
        closeWriter();
    }

    public static void getLog(String filePath, String key) {
        log.info("searching：{}", filePath);
        getLog(new File(filePath), key);
    }

    public static void getLog(File file, String key) {
        log.info("查询文件：{}", file.getAbsolutePath());
        writeLog(file.getAbsolutePath());
        try {
            FileReader fr = new FileReader(file);
            BufferedReader br = new BufferedReader(fr);
            br.lines().filter(l -> l.toLowerCase().contains(key)).forEach(ReadLog::writeLog);
        } catch (Throwable e) {
            log.error("异常：", e);
        }
    }

    private static BufferedWriter bw = null;

    static {
        try {
            bw = new BufferedWriter(new FileWriter("d:/log/tmp.txt"));
        } catch (Throwable e) {
            log.error("异常：", e);
        }
    }

    public static void writeLog(String logs) {
        try {
            bw.write(logs);
            bw.newLine();
        } catch (Throwable e) {
            log.error("异常：", e);
        }
    }

    private static void closeWriter() {
        if (bw != null) {
            try {
                bw.close();
            } catch (IOException e) {
                log.error("closeWriter fail:", e);
            }
        }
    }
}
